package com.easyioc.web;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ContextLoaderListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(ContextLoaderListener.class);
	
	private static final String CONFIG_LOCATION_PARAM = "easyIocContextConfigLocation";

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext servletContext = sce.getServletContext();
		WebBeanContext webBeanContext = initWebBeanContext(servletContext);
		servletContext.setAttribute(WebBeanContext.WEB_BEAN_CONTEXT_ATTRIBUTE, webBeanContext);		
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
	}

	private WebBeanContext initWebBeanContext(ServletContext servletContext) {
		if (servletContext.getAttribute(WebBeanContext.WEB_BEAN_CONTEXT_ATTRIBUTE) != null) {
			throw new IllegalStateException(
			        "Cannot initialize context because there is already a bean context present.");
		}

		servletContext.log("Initializing EasyIoC WebBeanContext");
		logger.info("WebBeanContext: initialization started");

		WebBeanContext beanContext = new WebClasspathPropertiesBeanContext();
		beanContext.setConfigLocation(loadConfigLocation(servletContext));
		beanContext.refresh();
		
		return beanContext;
	}
	
	private String loadConfigLocation(ServletContext servletContext) {
		return servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
	}
}